import uuid
from concurrent.futures import ThreadPoolExecutor
from pathlib import Path

from django.http import HttpRequest
from django.views.static import serve
from drf_spectacular.utils import extend_schema
from rest_framework import mixins, permissions, viewsets
from rest_framework.decorators import action
from rest_framework.request import Request
from rest_framework.response import Response

from api_case.models import Case as APICase
from ui_case.models import Case as UICase

from .models import RunResult, Suite
from .serializers import RunResultSerializer, SuiteSerializer
from .xiaomi import start_frame


# 处理yaml文件和log文件,serve这个视图中是下载的方式获取的
def static_serve(request: HttpRequest, path, document_root=None, show_indexes=False):
    resp = serve(request, path, document_root, show_indexes)

    # 如果访问的静态文件是日志文件,修改返回响应的响应头中Content-Type的值为text/css
    if resp.status_code == 200:
        if path.endswith(".log"):
            resp.headers["Content-Type"] = "text/css; charset=utf-8"

    return resp


pool = ThreadPoolExecutor(max_workers=6)


@extend_schema(tags=["Suite"])
class SuiteViewSets(viewsets.ModelViewSet):
    queryset = Suite.objects.all()  # 数据来源
    serializer_class = SuiteSerializer  # 数据格式

    # 执行测试套件(指定的测试套件,带有pk值的)
    @action(methods=["POST"], detail=True)
    def run_suite(self, request: Request, pk):
        """执行测试套件的接口"""
        obj: Suite = self.get_object()  # 得到用例的对象
        # obj = Suite.objects.get(id=pk)
        """执行测试套件中用例"""
        # 1.生成执行结果
        run_result = RunResult.objects.create(
            suite=obj,
            project=obj.project,
            path="",
        )

        # 2.生成yaml用例和excel用例
        # 生成的用例存放在什么地方
        path = Path("suite_cases") / f"suite_{obj.id}_{obj.name}_{uuid.uuid4()}"
        # 创建目录
        Path.mkdir(path, parents=True, exist_ok=True)

        # 更新path
        run_result: RunResult
        run_result.path = str(path)
        run_result.save()  # 千万记得保存！！！！！！

        # 生成yaml接口测试用例
        for api_case in obj.api_case_list.all():
            api_case: APICase
            api_case.save_yaml(path)
        # 生成excel接口测试用例
        for ui_case in obj.ui_case_list.all():
            ui_case: UICase
            ui_case.save_excel(path)
        # 获取api接口测试用的数量
        api_case_count = obj.get_api_case_count()
        # 3.启动框架
        #   1.启动子进程
        #   2.启动pytest测试框架,更新执行结果
        pool.submit(start_frame, path, run_result, api_case_count)

        return Response(
            {
                "code": 0,
                "msg": "用例执行成功,需要查看结果请调用结果查询接口,id传递result_id的值",
                "result_id": run_result.id,
            }
        )


# 视图集里面的Model视图集合：处理Model/使用Model
@extend_schema(tags=["Suite"])
class RunResultViewSets(viewsets.GenericViewSet, mixins.RetrieveModelMixin, mixins.ListModelMixin):
    queryset = RunResult.objects.all()  # 数据来源
    serializer_class = RunResultSerializer  # 数据格式

    permission_classes = [permissions.IsAuthenticated]  # 应用鉴权类
